let PayData = {};
layui.use(['form', 'http', 'public'], function () {
    onLoad(1);
});

function onLoad(type = 1) {
    let id = layui.public.GetQuery("id");
    layui.http.SendAjax(shopUrl + '/api/addon/orderinfo/', {order_id: id}, {token: localStorage.getItem('user_token')}, function (res) {
        let data = res.data || {};
        if (type == 1) {
            PayData = data;
            layui.public.ViewTpl(data, 'view_body_data', 'view_body');
        }
        let is_down = data.orders.is_down || 2;
        if (type == 2 && is_down == 1) {
            window.location.href = "/common/shop/confirm/?id=" + id;
        }
    })

}

function payInfo(pay_type = 1) {
    let id = layui.public.GetQuery("id");
    PayData.orders.pay_type = pay_type;
    layui.http.SendAjax(shopUrl + '/api/addon/pay/', {
        order_id: id,
        pay_type: pay_type
    }, {token: localStorage.getItem('user_token')}, function (res) {
        let data = res.data || {};
        let code = res.code || 203;
        let msg = res.msg || '支付错误';
        switch (Number(code)) {
            case 203:
                layer.alert(msg);//支付失败
                break;
            case 200:
                DownLocal(id);//下载到本地
                break;
            case 2:
                PayData.pay_info = data;
                SendPay();//发起支付
                break;
        }
    })
}

function DownLocal(order_id) {

    layui.http.SendAjax('/common/shop/download/', {order_id: order_id}, {utoken: localStorage.getItem('user_token')}, function (res) {
        if (res.code == 200) {
            let addon=res.data.addon || '';
            layer.confirm('下载成功，是否确定安装?', {icon: 3}, function () {
                Install(PayData.orders.addon_num);
            }, function () {
                layer.msg('取消安装');
            });
            return;
        }
        layer.alert(res.msg, {icon: 2});
    })
}

function Install(addon = '‘') {
    layui.http.SendAjax('/common/shop/install/', {addon: addon}, {}, function (res) {
        if (res.code == 200) {
            layer.alert(res.msg, {icon: 1});
            return;
        }
        layer.alert(res.msg, {icon: 2});
    })
}

function SendPay() {

    layui.public.ViewTpl(PayData, 'pay_body_data', 'view_body');
    setInterval(() => {
        onLoad(2);
    }, 5000);

}